<?php
class StrukturOrganisasiController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column1', meaning
	 * using one-column layout. See 'protected/views/layouts/column1.php'.
	 */
	public $layout='//layouts/column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
		//	'rights',
		);
	}
        
	public function allowedActions() 
        { 
            return ''; 
        }
        
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
        
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new StrukturOrganisasi;
                
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['StrukturOrganisasi']))
		{
                  
                    $model->attributes=$_POST['StrukturOrganisasi'];
                    
                    if(!empty($_POST['StrukturOrganisasi']['parent_id']))
                    {
                        $root = StrukturOrganisasi::model()->findByPk($_POST['StrukturOrganisasi']['parent_id']);
                        $model->appendTo($root);
                        
                        StrukturOrganisasi::model()->updateByPk(
                                $model->id,
                                array(
                                    'parent_id' => $_POST['StrukturOrganisasi']['parent_id']
                                    )
                                );
                    }
                    else 
                    {
                        $model->saveNode();
                    }
			
                    $this->redirect(array('index'));
		}

		$this->render('create',array(
			'model'=>$model,
                        'list' => $this->reformatList()
		));
	}

        /**
         *  @access public
         *  @param type $id 
         */
        public function actionDown($id){
            $model=$this->loadModel($id);
            $model->moveDown($id);
            $this->redirect(array('index'));
        }


        /**
         * @access public
         * @param Int $id 
         */
        public function actionUp($id){
            $model=$this->loadModel($id);
            $model->moveUp($id);
            $this->redirect(array('index'));    
        }
        
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['StrukturOrganisasi']))
		{
                  
                    $model->attributes=$_POST['StrukturOrganisasi'];
                    
                    if(!empty($_POST['StrukturOrganisasi']['parent_id']))
                    {
                        $parent = StrukturOrganisasi::model()->findByPk($_POST['StrukturOrganisasi']['parent_id']);
                        $model->moveAsFirst($parent);
                        
                        StrukturOrganisasi::model()->updateByPk(
                                $id,
                                array(
                                    'parent_id' => $_POST['StrukturOrganisasi']['parent_id'],
                                    'nama' => $_POST['StrukturOrganisasi']['nama']
                                    )
                                );
                    }
                    else 
                    {
                        $data = StrukturOrganisasi::model()->findByPk($id);
                        if(!$data->isRoot())
                        {
                            $model->moveAsRoot();
                        }
                        
                        $model->updateByPk(
                                $id, 
                                array(
                                    'nama' => $_POST['StrukturOrganisasi']['nama']
                                )
                              );
                        
                    }
			
                    $this->redirect(array('index'));
		}

		$this->render('update',array(
			'model'=>$model,
                        'list' => $this->reformatList()
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
            $model = $this->loadModel($id);
            $children = $model->children()->findAll();
            
            if(empty($children))
                  $model->deleteNode();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{       
                
		$model=new StrukturOrganisasi('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['StrukturOrganisasi']))
			$model->attributes=$_GET['StrukturOrganisasi'];
                
		$this->render('index',array(
			'model'=>$model,
                        'data' =>$model->getList()
		));
	}

        /**
         * reformat List 
         * @return Array
         */
	protected function reformatList() {
            $result = array();
            $model  = new StrukturOrganisasi;
            $data   = $model->getList();
            foreach($data as $key=>$value){
                $result[$key] = $value['nama'];
            }
            return $result;
        }

        /**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=StrukturOrganisasi::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='struktur-organisasi-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
